package edu.iss.demo.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.iss.demo.exception.EmployeeNotFound;
import edu.iss.demo.exception.UserDetailNotFound;
import edu.iss.demo.model.Employee;
import edu.iss.demo.model.UserDetail;
import edu.iss.demo.repository.EmployeeRepository;
import edu.iss.demo.repository.UserDetailRepository;
@Service
public class UserDetailServiceImpl implements UserDetailService {

	
	
	@Resource
	UserDetailRepository userDetailRepository;

	@Override
	@Transactional
	public UserDetail create(UserDetail userDetail) {
		UserDetail detail = userDetail;
		return userDetailRepository.save(detail);
	}

	@Override
	@Transactional(rollbackFor = UserDetailNotFound.class)
	public UserDetail delete(long id) throws UserDetailNotFound {
		UserDetail deletedUserDetail= userDetailRepository.findOne(id);

		if (deletedUserDetail== null)
			throw new UserDetailNotFound();

		userDetailRepository.delete(deletedUserDetail);
		return deletedUserDetail;
	}

	@Override
	@Transactional
	public List<UserDetail> findAll() {
		
		return userDetailRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor = UserDetailNotFound.class)
	public UserDetail update(UserDetail userDetail) throws UserDetailNotFound {
		UserDetail updatedUserDetail = userDetailRepository.findOne(userDetail.getUserId());

		if (updatedUserDetail == null)
			throw new UserDetailNotFound();

		updatedUserDetail.setEmployeeId(userDetail.getEmployeeId());
		updatedUserDetail.setPassword(userDetail.getPassword());
		
		
		userDetailRepository.flush();
		return updatedUserDetail;
	}

	@Override
	@Transactional
	public UserDetail findById(long id) {
		return userDetailRepository.findOne(id);
	}

}
